// pages/detail/detail.js
var Bmob = require('../../dist/Bmob-1.6.0.min.js');
const {
  $Toast
} = require('../../dist/base/index');
var app = getApp()
const {
  $Message
} = require('../../dist/base/index');

Page({


  /**
   * 页面的初始数据
   */
  data: {
    displaystate: 'none',
    iconurl: '../../images/+h.png',
    colorArr: ["blue", "green", "red", "pink", "yellow"],
    randomColor: [],

    animationtext: '',
    animationtextflag: '',
    objectId: '',
    objectId_user: '',
    animation: '',
    animationflag: 0,
    title: "现在没有任何数据",
    name: "null",
    imageurl: "http://npic7.edushi.com/cn/zixun/zh-chs/2018-06/15/9a9ce41b2071431ab76a1cf1bdeb345c.jpg",
    content: "现在没有任何数据",
    tag: ["学习", "自习"],
    imgs: [],

    isOk: false


  },
  getLabelColor: function() {
    let that = this
    var colorLen = this.data.colorArr.length;
    var colorArr = this.data.colorArr;
    var newcolorArr = [];
    var pre = null;
    newcolorArr = [];
    for (var j = 0; j < that.data.tag.length; j++) {
      while (random == pre) {
        var random = colorArr[Math.floor(Math.random() * colorLen)];
      }
      pre = random;
      newcolorArr.push(random);
    }
    this.setData({
      randomColor: newcolorArr
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this
    var had = false


    //开始加载
    // console.log("getCurrentPages", getCurrentPages())
    //保存当前posting的id 和 userid
    that.setData({
      objectId: options.objectId,
      // 这是调试用的 正式版本请将下列代码取消屏蔽
      objectId_user: app.globalData.authData.objectId
      // objectId_user: '6a634ce6a9'
    })

    // that.handleLoadingStart()
    const query = Bmob.Query("Postings");
    query.include('user', 'post')
    query.get(options.objectId).then(res => {
      console.log('Postings', res)
      var label_list;
      const query1 = Bmob.Query("label")
      query1.statTo("where", '{"$relatedTo":{"object":{"__type":"Pointer","className":"Postings","objectId":"' + res.objectId + '"},"key":"tag"}}');
      // query1.statTo("where", '{"tag":{"$inQuery":{"where":{"tag":"乒乓球"},"className":"label"}}}');
      query1.find().then(res1 => {
        //在这里查找一下之前有没有follow过这个人
        const query2 = Bmob.Query("UserData")
        query2.statTo("where", '{"follow":{"$inQuery":{"where":{"objectId":"' + res.objectId + '"},"className":"Postings"}}}');
        query2.equalTo("objectId", "==", that.data.objectId_user)
        query2.find().then(res4 => {
          if (res4.length) {


            var flag = that.data.iconurl;
            var textflag = that.data.displaystate;
            that.animationtext = wx.createAnimation({
              duration: 150,
              timingFunction: 'linear',
              transformOrigin: 'center',
            })
            that.animation = wx.createAnimation({
              duration: 150,
              timingFunction: 'linear',
              transformOrigin: 'center',
            })
            that.animation.rotate(45).step();
            that.animationtext.scale(0).step();
            // that.animationtext.translate(600).step();
            that.setData({
              animationflag: 1,

            })
            textflag = ''
            flag = "../../images/+.png"
            that.setData({
              animation: that.animation.export(),
              animationtext: that.animationtext.export(),
              iconurl: flag,


            })
            if (that.data.animationflag == 1) {
              setTimeout(function() {

                that.setData({
                  displaystate: textflag
                })
              }.bind(that), 150)
            } else {
              that.setData({
                displaystate: textflag
              })

            }

          }

        })




        //查找UserData
        const pointer = Bmob.Pointer('_User')
        const poiID = pointer.set(res.user.objectId)

        const query = Bmob.Query('UserData')
        query.include('major', 'post')
        query.equalTo("user", "==", poiID);
        query.find().then(res2 => {

          // var dataId = res2[0].objectId
          // const query2 = Bmob.Query("Postings")
          // query2.statTo("where", '{"$relatedTo":{"object":{"__type":"Pointer","className":"UserData","objectId":"' + dataId + '"},"key":"follow"}}');
          // // console.log("dataid",dataId)
          // // query2.equalTo("objectId", "==", dataId)
          // query2.find().then(res3 => {
          //   console.log("查找有没有符合条件的Posting", res3)
          //   if (res3.length) {
          //     console.log("查询到相关信息")
          //   } else {
          //     console.log("没有查询到相关信息")
          //   }
          // })



          label_list = []
          for (var j = 0; j < res1.length; j++) {
            label_list.push(res1[j].tag);
          }
          //把帖子的数据存入list
          //判断一下有没有图片
          if (res.imgs) {
            //如果有图片就放进去
            that.setData({
              imgs: res.imgs
            })
          } else {
            //如果没有图片就置空
            that.setData({
              imgs: null
            })
          }
          if (res2.length) {
            //如果服务器端有pic和nickname
            that.setData({
              title: res.title,
              user: res.user,
              content: res.detail,
              tag: label_list,
              name: res2[0].nickName,
              imageurl: res2[0].userPic.url,
            })
          } else {
            that.setData({
              //如果服务器没有UserData
              title: res.title,
              user: res.user,
              content: res.detail,
              tag: label_list,
              name: res.user.nickName,
              imageurl: res.user.userPic,
            })
          }
          that.getLabelColor()
          //结束加载（加载成功
          that.handleLoadingStop()
        })
        // console.log(that.data.array)
      }).catch(err => {
        //结束加载（加载失败
        console.log(err)
      })

    }).catch(err => {
      //结束加载（加载失败
      console.log(err)
    })

  },
  //初始加载图标样式的函数，依据animationflag
  loadicon: function() {
    if (this.data.animationflag == 0) {
      this.setData({
        displaystate: 'none',
        iconurl: '../../images/+h.png',
      })
    } else {
      this.setData({
        displaystate: '',
        iconurl: '../../images/+.png',
      })
    }
  },
  handleLoadingStart() {
    $Toast({
      content: '加载中',
      type: 'loading',
      duration: 0
    });
  },
  handleLoadingStop() {
    // $Toast.hide()
    this.setData({
      isOk: true
    })
  },
  chooseImage: function(e) {
    var that = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        that.setData({
          files: that.data.files.concat(res.tempFilePaths)
        });
      }
    })
  },
  previewImage: function(e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.imgs // 需要预览的图片http链接列表
    })
  },
  rotate: function() {
    var flag = this.data.iconurl;
    var textflag = this.data.displaystate;
    if (this.data.animationflag == 0) {
      this.add()
      this.animationtext = wx.createAnimation({
        duration: 150,
        timingFunction: 'linear',
        transformOrigin: 'center',
      })
      this.animation = wx.createAnimation({
        duration: 150,
        timingFunction: 'linear',
        transformOrigin: 'center',
      })
      this.animation.rotate(45).step();
      this.animationtext.scale(0).step();
      // this.animationtext.translate(600).step();
      this.setData({
        animationflag: 1,

      })
      textflag = ''
      flag = "../../images/+.png"
    } else {
      //delete
      this.delete()
      this.animationtext = wx.createAnimation({
        duration: 150,
        timingFunction: 'linear',
        transformOrigin: 'center',
      })
      this.animation = wx.createAnimation({
        duration: 150,
        timingFunction: 'linear',
        transformOrigin: 'center',
      })

      this.animation.rotate(-90).step();
      this.animationtext.scale(1).step();
      console.log("test,now the animationflag is false")
      this.setData({
        animationflag: 0,
      })
      textflag = 'none'
      flag = "../../images/+h.png"
    }
    this.setData({
      animation: this.animation.export(),
      animationtext: this.animationtext.export(),
      iconurl: flag,


    })
    if (this.data.animationflag == 1) {
      setTimeout(function() {

        this.setData({
          displaystate: textflag
        })
      }.bind(this), 150)
    } else {
      this.setData({
        displaystate: textflag
      })
    }

  },
  add: function() {
    console.log("申请加入" + this.data.objectId)
    console.log("userid", this.data.objectId_user)
    const query = Bmob.Query('UserData');
    query.statTo("where", '{"user":{"$inQuery":{"where":{"objectId":"' + this.data.objectId_user + '"},"className":"_User"}}}');
    const relation = Bmob.Relation('Postings')
    const relID = relation.add([this.data.objectId])
    query.find().then(res => {
      console.log("找到用户信息", res)
      res.set('follow', relID)
      res.saveAll().then(res => {
        // 成功修改
        console.log('信息加入成功', res)
      }).catch(err => {
        console.log(err)
      });
    }).catch(err => {
      console.log(err)
    })
    // const query = Bmob.Query("UserData")
    //查找对应的UserData
    // query1.statTo("where", '{"$relatedTo":{"object":{"__type":"Pointer","className":"Postings","objectId":"' + res.objectId + '"},"key":"tag"}}');
    // query1.statTo("where", '{"tag":{"$inQuery":{"where":{"objectId":"'++'"},"className":"_User"}}}');
    // query1.find().then(res1 => {

    // })
  },
  delete: function() {
    console.log("取消申请" + this.data.objectId)
    console.log("userid", this.data.objectId_user)
    const query = Bmob.Query('UserData');
    query.statTo("where", '{"user":{"$inQuery":{"where":{"objectId":"' + this.data.objectId_user + '"},"className":"_User"}}}');
    const relation = Bmob.Relation('Postings')
    const relID = relation.remove([this.data.objectId])
    query.find().then(res => {
      console.log("找到用户信息", res)
      res.set('follow', relID)
      res.saveAll().then(res => {
        // 成功删除
        console.log('信息删除成功', res)
      }).catch(err => {
        console.log(err)
      });
    }).catch(err => {
      console.log(err)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

})